package com.spring.cloud.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.spring.cloud.enums.ErrorMsgEnum;
import com.spring.cloud.exception.BusinessException;
import com.spring.cloud.mapper.UserMapper;
import com.spring.cloud.pojo.User;
import com.spring.cloud.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    private static final String KEY_PREFIX = "cloud:verify:code:";

    public User queryUser(String username, String password) {
        QueryWrapper qw =new QueryWrapper();
        qw.eq("username",username);

        //首先根据用户名查询用户
        User user = userMapper.selectOne(qw);

        if (user == null) {
            throw BusinessException.of(ErrorMsgEnum.E1,"用户不存在");
        }

        //检验密码是否正确
        if (!StringUtils.equals(CodecUtils.md5Hex(password, user.getSalt()), user.getPassword())) {
            //密码不正确
            throw BusinessException.of(ErrorMsgEnum.E1);
        }

        return user;
    }

    public void addUser(User user) {
        user.setId(IdWorker.getId());
        user.setCreated(new Date());
        String key = KEY_PREFIX + user.getPhone();

        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);

        //生成密码
        String md5Pwd = CodecUtils.md5Hex(user.getPassword(), user.getSalt());

        user.setPassword(md5Pwd);

        //保存到数据库
        int count = userMapper.insert(user);

        if (count != 1) {
            throw BusinessException.of(ErrorMsgEnum.E10003);
        }

    }
}
